﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;
using Microsoft.Phone.Tasks;

namespace Webtextr
{
    public partial class MainPage : PhoneApplicationPage
    {
        string baseUrl;
        string username;
        string password;
        string network;

        private PhoneNumberChooserTask _choosePhoneNumber;
        private WebClient _webClient;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            _choosePhoneNumber = new PhoneNumberChooserTask();
            _choosePhoneNumber.Completed += new EventHandler<PhoneNumberResult>(_choosePhoneNumber_Completed);

            _webClient = new WebClient();
            _webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(_webClient_DownloadStringCompleted);
            
        }

        void _webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            sendingOverlay.Visibility = Visibility.Collapsed;
            ApplicationBar.IsVisible = true;

            String resultText = "";

            try
            {
                int responseCode = Int32.Parse(e.Result);

                if (responseCode >= 0)
                {
                    resultText = "Message sent successfully. You have " + responseCode + " webtexts remaining.";
                }
                else if (responseCode == -1)
                {
                    resultText = "Error: Invalid login details.";
                }
                else if (responseCode == -2)
                {
                    resultText = "Error: Unable to connect to phone network's website.";
                }
                else if (responseCode == -5)
                {
                    resultText = "Error: Unexpected response from phone network's website.";
                }
                else
                {
                    resultText = "Unknown error: " + responseCode;
                }
            }
            catch
            {
                resultText = "Invalid response from server.";
            }

            MessageBox.Show(resultText);
        }

        private void SendSmsClick(object sender, EventArgs e)
        {
            StorageHelper helper = new StorageHelper();
            UserSettings settings = helper.LoadSettings();
            if (settings != null)
            {
                if (recipient.Text.Length > 0 && msgText.Text.Length > 0)
                {
                    baseUrl = settings.baseUrl;
                    username = settings.username;
                    password = settings.password;
                    network = settings.network;


                    string cRecipient = HttpUtility.UrlEncode(recipient.Text);
                    string cMsgText = HttpUtility.UrlEncode(msgText.Text);

                    string sendUrl = baseUrl + "?u=" + username + "&p=" + password
                        + "&s=" + network + "&d=" + cRecipient + "&m=" + cMsgText;

                    _webClient.DownloadStringAsync(new Uri(sendUrl));
                    sendingOverlay.Visibility = Visibility.Visible;
                    ApplicationBar.IsVisible = false;
                    sendingProgressBar.Focus();
                }
            }
            else
            {
                MessageBox.Show("Please configure your webtext user account in Settings.");
                NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
            }
            
        }

        private void SettingsPageClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
        }
        private void AboutClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));
        }
        private void ClearClick(object sender, EventArgs e)
        {
            msgText.Text = "";
        }
        private void ChooseContactClick(object sender, RoutedEventArgs e)
        {
            _choosePhoneNumber.Show();
        }

        void _choosePhoneNumber_Completed(object sender, PhoneNumberResult e)
        {
            try
            {
                (Application.Current as App).recipientContents = e.PhoneNumber;
            }
            catch { }
        }

        private void PhoneApplicationPage_Loaded(object sender, EventArgs e)
        {

        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            (Application.Current as App).recipientContents = recipient.Text;
            (Application.Current as App).msgTextContents = msgText.Text;
            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                recipient.Text = (Application.Current as App).recipientContents;
                msgText.Text = (Application.Current as App).msgTextContents;
            }
            catch { }
            base.OnNavigatedTo(e);
        }
    }
}